<?php

namespace app\api\controller;

use app\admin\model\Camera;
use app\admin\model\Maintenance;
use app\common\controller\Api;
use app\common\model\CarPurchaseIntention;
use app\common\model\CarSelect;
use app\common\model\Guarantee;
use app\common\model\Order;
use app\common\model\OrderBindCameraModel;
use app\common\model\OrderInfo;
use app\common\model\Problem;
use app\common\model\VehicleBindCarmeraModel;
use app\common\model\VehicleBindCatModel;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use think\cache\driver\Redis;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use Yansongda\Pay\Pay as ysPay;
use think\Image;
//
//sk
//uu_pKzuT_qlUcdi9slKBwocpvP2V3LpwFnz9fckq
//ak
//bzeHEixzlarlkKnYUEDvnmfPjt6FZfYx2UH4E7w2
//
//
//ocr vin
//6927709
//ZzD9cKHAqGsZVioem43RUzbB
//EXY8DgGXN2xgKhfQzXquBlLOzHVImNmm

//车检
class Vehicle extends Api
{
    protected $noNeedLogin = ['getBatteryOrderDetail','getVinCode', 'generateDoc', 'getMaintenance', 'getVehicleList', 'getVehicleDetail', 'getOrderInfo', 'getOrderInfoChild', 'getOverhaulStatusList', 'setCarRound', 'addRemake', 'carSelectList', 'carSelectDetail'];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        check_cors_request();
        parent::_initialize();
    }

    /**
     * 获取车检列表
     * @return void
     * @throws \think\exception\DbException
     */
    public function getVehicleList()
    {
        $model = new \app\common\model\Vehicle();
        $list = $model->paginate();
        $this->success('成功', $list);
    }

    /**
     * 查看详情
     */
    public function getVehicleDetail()
    {
        $id = $this->request->param('id');
        if (!$id) {
            $this->error('无效的数据');
        }
        $model = new \app\common\model\Vehicle();
        $info = $model->get($id);
        //获取检测内容
        $category = new \app\common\model\Category();
        $vehicleBindCatModel = new  VehicleBindCatModel();
        $firstCatIds = array_unique($vehicleBindCatModel->where('vehicle_id', $id)->column('first_cat_id'));
        $catIds = array_unique($vehicleBindCatModel->where('vehicle_id', $id)->column('cat_id'));
        $categoryList = $category->whereIn('id', $firstCatIds)->field('id,name,image,type,flag')->select();
        foreach ($categoryList as $k => &$v) {
            $v['image'] = get_app_image_url($v['image']);
            $overhaul = toArray($category->where('pid', $v['id'])->whereIn('id', $catIds)->field('id,name,image,type,flag')->select());
            if ($overhaul) {
                foreach ($overhaul as $key => &$v2) {
                    $v2['image'] = get_app_image_url($v2['image']);
                }
            }
            $v['overhaul'] = $overhaul;
            $v['overhaulNum'] = count($v['overhaul']);
        }
        $info['category'] = $categoryList;
        $this->success('成功', $info);
    }

    /**
     * 创建订单1
     */
    public function createOrder()
    {
        $id = $this->request->param('id');
        if (!$id) {
            $this->error('请选择检查项目');
        }
        $mobile = input('mobile/d');
        if (!$mobile) {
            $this->error('请填写手机号');
        }
        $car_name = $this->request->param('car_name');//车辆型号
        if (!$car_name) {
            $this->error('请填写车辆型号');
        }
        $energy_type = $this->request->param('energy_type');//'能源类型:1=新能源,2=燃油车',
        if (!$energy_type) {
            $this->error('请设置能源类型');
        }
        $vin = $this->request->param('vin');//'能源类型:1=新能源,2=燃油车',
        if (!$vin) {
            $this->error('请设置vin');
        }
        $vin_image = $this->request->param('vin_image');//'能源类型:1=新能源,2=燃油车',
        if (!$vin_image) {
            $this->error('请上传行驶证');
        }
        $up_address = $this->request->param('up_address');//'能源类型:1=新能源,2=燃油车',
        if (!$up_address) {
            $this->error('请设置上门地址');
        }
        $up_time = $this->request->param('up_time');//'能源类型:1=新能源,2=燃油车',
        if (!$up_time) {
            $this->error('请设置上门时间');
        }
        $contacts = $this->request->param('contacts');//'能源类型:1=新能源,2=燃油车',
        if (!$contacts) {
            $this->error('请设置联系人');
        }
        $remark = $this->request->param('remark');
        $vehicleModel = new \app\common\model\Vehicle();
        $info = $vehicleModel->where('id', $id)->find();
        if (!$info) {
            $this->error('请选择检查不存在');
        }
        $orderModel = new Order();
        $orderInfoModel = new OrderInfo();
        $vehicleBindCatModel = new  VehicleBindCatModel();
        $firstCatIds = array_unique($vehicleBindCatModel->where('vehicle_id', $id)->column('first_cat_id'));
        $catIds = array_unique($vehicleBindCatModel->where('vehicle_id', $id)->column('cat_id'));
        $cameraModel = new  Camera();
        $orderBindCameraModel = new  OrderBindCameraModel();
//        $vehicleBindCameraModel = new  VehicleBindCarmeraModel();
        //查询当前检查项目的摄像头
//        $cameraIds = $vehicleBindCameraModel->where('vehicle_id', $id)->column('camera_id');
        // 启动事务
        Db::startTrans();
        try {
            $orderId = $orderModel->insertGetId([
                'price' => $info['price'],
                'order_sn' => build_order_no(),
                'category_ids' => $info['category_ids'],
                'mobile' => $mobile,
                'user_id' => $this->auth->id,
                'status' => 1,
                'vehicle_id' => $id,
                'car_name' => $car_name,
                'energy_type' => $energy_type,
                'vin' => $vin,
                'vin_image' => $vin_image,
                'up_address' => $up_address,
                'up_time' => $up_time,
                'contacts' => $contacts,
                'remark' => $remark ?? '',
                'vehicle_name' => $info['name'],
                'createtime' => time(),
                'updatetime' => time()
            ]);
            $category = new \app\common\model\Category();
//            $overhaulModel = new \app\common\model\Overhaul();
            $categoryList = toArray($category->whereIn('id', $catIds)->field('id,name,pid,image,type,flag')->order('weigh desc,id desc')->select());
            $insertData = [];
            foreach ($categoryList as $k => $v) {
                $insertData[$k] = array('order_id' => $orderId,
                    'overhaul_id' => $v['id'],
                    'overhaul_name' => $v['name'],
                    'first_cat_id' => $v['pid'],
                );
            }
            $orderInfoModel->insertAll($insertData);

            // 一次性查询所有符合条件的摄像头信息
            $cameras = $cameraModel
//                ->whereIn('id', $cameraIds)
                ->where('status', 1)
                ->select();

            // 构造订单绑定摄像头数据
            $orderBindCameraInsert = [];
            foreach ($cameras as $cameraInfo) {
                $orderBindCameraInsert[] = [
                    'order_id' => $orderId,
                    'camera_id' => $cameraInfo['id'],
                    'camera_image' => $cameraInfo['image'],
                    'camera_name' => $cameraInfo['name'],
                ];
            }
//            dd($orderBindCameraInsert);

            // 批量插入
            if (!empty($orderBindCameraInsert)) {
                $orderBindCameraModel->insertAll($orderBindCameraInsert);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {

            // 回滚事务
            $this->error('创建失败' . $e);
        }
        $this->success('成功', ['order_id' => $orderId]);
    }

    /**
     * 订单列表
     */
    public function getOrderList()
    {
        $type = $this->request->param('type');//2 代表查询师傅端的
        $status = $this->request->param('status');//状态:1=待支付,2=待接单,3=待检查,4=完成
        $userType = $this->auth->type;
        $where = [];
        $orderModel = new Order();
        $list = $orderModel;

        if ($type == 2) {
            if ($userType != 2) {
                $this->error('无权查看');
            }
            $where['detection_id'] = $this->auth->id;
            if ($status == 2) {
                $where['status'] = 2;
                $where['detection_id'] = 0;
            } else {
                $where['status'] = $status;

            }
        } else {
            $where['user_id'] = $this->auth->id;
            if ($status) {
                $where['status'] = $status;
            }
        }

        $list = $list->where($where)->order('id desc')->paginate();

        $this->success('成功', $list);
    }

    /**
     * 查看订单详情
     */
    public function getOrderInfo()
    {
        $order_id = $this->request->param('order_id');
        if (!$order_id) {
            $this->error('无效的订单');
        }
        $orderModel = new Order();
        $orderInfo = $orderModel->where('id', $order_id)->find();
        $orderInfoModel = new OrderInfo();
        $category = new \app\common\model\Category();
//        $orderInfo['infos'] = $orderInfoModel->where('order_id', $order_id)->column('first_cat_id');
//        dd($orderInfoModel->where('order_id', $order_id)->column('first_cat_id'));
//        $orderInfo['infos'] = $category->whereIn('id', $orderInfoModel->where('order_id', $order_id)->column('first_cat_id'))->where('pid',0)->field('id,name,image,type,flag')->select()->each(function ($item) {
//            $item['image'] = get_app_image_url($item['image']);
//        });
        $categoryList = $category->whereIn('id', $orderInfoModel->where('order_id', $order_id)->column('first_cat_id'))->field('id,name,image,type,flag')->select();
        foreach ($categoryList as $k => &$v) {
            $v['image'] = get_app_image_url($v['image']);
            $v['allNum'] = $orderInfoModel->where('order_id', $order_id)->where('first_cat_id', $v['id'])->count();
            $v['allVehicleNum'] = $orderInfoModel->where('order_id', $order_id)->where('first_cat_id', $v['id'])->where('overhaul_status', -1)->count();
        }
//        $orderInfo['category'] = $categoryList;
        $orderInfo['infos'] = $categoryList;
        //获取订单绑定摄像头信息
        $orderBindCameraModel = new OrderBindCameraModel();
        $cameraData = $orderBindCameraModel->where('order_id', $order_id)->select();

//dd($orderInfo['camera'])
        if ($cameraData) {
            $cameraData = collection($cameraData)->toArray();
            foreach ($cameraData as $k => &$v1) {
                if (!empty($v1['camera_image'])) {
                    $v1['camera_image'] = get_app_image_url($v1['camera_image']);
                }
                if (!empty($v1['image'])) {
                    $v1['image'] = get_app_image_url($v1['image']);
                }
            }
        }
        if (!$orderInfo['car_round']) {
            $orderInfo['car_round'] = getCarRoundList();
        } else {
            $carRound = json_decode($orderInfo['car_round'], true);
            foreach ($carRound as &$image) {
                $image['image'] = get_app_image_url($image['image']);
            }
            $orderInfo['car_round'] = $carRound;
        }
        $orderInfo['camera'] = $cameraData;
        $orderInfo['vin_image'] = $orderInfo['vin_image'] ? get_app_image_url($orderInfo['vin_image']) : '';
        $this->success('成功', $orderInfo);
    }

    /**
     * 获取下级
     */
    public function getOrderInfoChild()
    {
        $order_id = $this->request->param('order_id');
        if (!$order_id) {
            $this->error('无效的订单');
        }
        $pid = input('pid');
        if (!$pid) {
            $this->error('无效的检查项目');
        }
        $orderInfoModel = new OrderInfo();
//            $orderInfoModel->where('order_id', $order_id)->where('first_cat_id', $pid)->select();
        $list = $orderInfoModel->where('order_id', $order_id)->where('first_cat_id', $pid)->select();
        foreach ($list as &$v) {
            if ($v['overhaul_remark_image']) {
                $v['overhaul_remark_image'] = get_app_array_image_url(explode(',', $v['overhaul_remark_image']));
            }
        }
        $this->success('成功', $list);
    }

    /**
     * 师傅端领取订单
     */
    public function receiveOrder()
    {
        $order_id = $this->request->param('order_id');
        if (!$order_id) {
            $this->error('无效的订单');
        }
        $orderModel = new Order();
        $orderInfo = $orderModel->where('id', $order_id)->where('status', '=', 2)->find();
        if (!$orderInfo) {
            $this->error('无效的订单');
        }
        $userType = $this->auth->type;

        if ($userType != 2) {
            $this->error('无权操作');
        }
        $orderModel->where('id', $order_id)->update(['status' => 3, 'detection_id' => $this->auth->id, 'taking_time' => time()]);
        $this->success('成功', []);
    }

    /**
     * 检测订单
     */
    public function detectionOrder()
    {
        $order_id = $this->request->param('order_id');
        $register_time = $this->request->param('register_time');//登记日期
        $first_cat_id = $this->request->param('first_cat_id');//一级检测项目
        $mileage = $this->request->param('mileage');//行驶里程
        $use_type = $this->request->param('use_type');//使用性质:1=营运车,2=非营运
        $car_type = $this->request->param('car_type');//车辆类型:1=轿车,2=SUV
        $infos = strip_tags(htmlspecialchars_decode($this->request->param('infos')));//检测项目json [{"overhaul_id":1,"overhaul_remark":"备注","overhaul_remark_image":"图片地址","overhaul_status":1}]

        if (!$order_id) {
            $this->error('无效的订单');
        }

        $orderModel = new Order();
        $orderInfoModel = new OrderInfo();
        $orderInfo = $orderModel->where('id', $order_id)->find();
        if (!in_array($orderInfo['status'], [3, 6, 5])) {
            $this->error('订单状态错误');
        }

//         启动事务
        Db::startTrans();
        try {

            foreach (json_decode($infos, true) as $k => $v) {
                $overhaul_remark_images = '';
                if ($v['overhaul_remark_image']) {
                    $overhaul_remark_images = explode(',', $v['overhaul_remark_image']);
                    foreach ($overhaul_remark_images as $k1 => &$v1) {
                        if ($v1) {
                            if (!strpos($v1, 'watermark')) {
                                $v1 = $v1 . '?watermark/2/fontsize/700/gravity/NorthWest/text/' . base64_encode(date('Y-m-d H:i:s'));
                            }
                        }
                    }
                    $overhaul_remark_images = implode(',', $overhaul_remark_images);
                }
                $orderInfoModel->where('order_id', $order_id)->where('overhaul_id', $v['overhaul_id'])->where(['first_cat_id' => $first_cat_id])->update(
                    ['overhaul_remark' => $v['overhaul_remark'], 'overhaul_status' => $v['overhaul_status'], 'overhaul_remark_image' => $overhaul_remark_images, 'testing_time' => time()]
                );
            }
//            if ($orderInfoModel->where('order_id', $order_id)->where('overhaul_status', 0)->count() == 0) {
//                $orderModel->where('id', $order_id)->update(['status' => 5]);
//            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            $this->error('创建失败' . $e);
        }
        $this->success('成功', []);
    }

    /**
     * 激活保障
     */
    public function activationGuarantee()
    {
        $order_sn = input('order_sn');
        $transfer_time = input('transfer_time');
        $contract_images = input('contract_images');
        $driving_license = input('driving_license');//行驶证
        $vehicle_registration = input('vehicle_registration');//车辆登记证书
        $vehicle_acquisition = input('vehicle_acquisition');//车辆购置证明
        $second_hand_invoices = input('second_hand_invoices');//二手发票
        $mobile = input('mobile');
        if (!$order_sn || !$transfer_time || !$contract_images || !$mobile) {
            $this->error('请完善信息');
        }
        $user_id = $this->auth->id;
        $orderModel = new Order();
        $orderInfo = $orderModel->where('order_sn', $order_sn)->find();
        if (!$orderInfo) {
            $this->error('记录不存在');
        }
        $guaranteeModel = new Guarantee();
        $guaranteeInfo = $guaranteeModel->where('order_sn', $order_sn)->find();
        if ($guaranteeInfo) {
            $this->error('当前报告号已被使用');
        }
        $guaranteeModel->insert([
            'user_id' => $user_id,
            'order_sn' => $order_sn,
            'transfer_time' => $transfer_time,
            'contract_images' => $contract_images,
            'mobile' => $mobile,
            'driving_license_image' => $driving_license,
            'vehicle_registration_image' => $vehicle_registration,
            'vehicle_acquisition_image' => $vehicle_acquisition,
            'second_hand_invoices_image' => $second_hand_invoices,
        ]);
        $this->success('成功', []);
    }

    /**
     * 问题列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\except\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function getProblemList()
    {
        $type = input('type', 1);
        $model = new Problem();
        $list = $model->where('type', $type)->order('id desc')->select();
        $this->success('成功', $list);
    }

    /**
     * 设置订单摄像头
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function setOrderCamera()
    {
        $order_id = input('order_id', 1);

        $infos = strip_tags(htmlspecialchars_decode($this->request->param('infos')));//检测项目json [{"id":1,"image":"备注"}]
        $orderModel = new Order();
        $orderInfo = $orderModel->where('id', $order_id)->find();
        if (!$orderInfo) {
            $this->error('订单不存在');
        }
        if (!in_array($orderInfo['status'], [3, 6])) {
            $this->error('订单状态错误');
        }
        $orderBindCameraModel = new  OrderBindCameraModel();

        Db::startTrans();
        try {
            foreach (json_decode($infos, true) as $k => $v) {
                if ($v['image']) {
                    if (!strpos($v['image'], 'watermark')) {
                        $image = $v['image'] . '?watermark/2/fontsize/700/gravity/NorthWest/text/' . base64_encode(date('Y-m-d H:i:s'));
                        $orderBindCameraModel->where('order_id', $order_id)->where('id', $v['id'])->update(['image' => $image]);
                    }
                }

            }
            if ($orderModel->where('id', $order_id)->update(['status' => 6]) === false) {
                throw new \think\Exception('保存失败');
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            $this->error('创建失败' . $e);
        }
        $this->success('成功', []);
    }

    /**
     * 设置车辆周围图片
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function setCarRound()
    {
        $order_id = input('order_id', 1);

        $infos = strip_tags(htmlspecialchars_decode($this->request->param('infos')));//检测项目json [{"image":1,"desc":"车辆右后"}]
        $orderModel = new Order();
        $orderInfo = $orderModel->where('id', $order_id)->find();
        if (!$orderInfo) {
            $this->error('订单不存在');
        }
        if (!in_array($orderInfo['status'], [3, 6])) {
            $this->error('订单状态错误');
        }
        $orderBindCameraModel = new  OrderBindCameraModel();

        Db::startTrans();
        try {
            $infos = json_decode($infos, true);
            foreach ($infos as $k => &$v) {
                if ($v['image']) {
                    if (!strpos($v['image'], 'watermark')) {
                        $v['image'] = $v['image'] . '?watermark/2/fontsize/700/gravity/NorthWest/text/' . base64_encode(date('Y-m-d H:i:s'));
                    }
                }
            }
            if ($orderModel->where('id', $order_id)->update(['car_round' => json_encode($infos)]) === false) {
                throw new \think\Exception('保存失败');
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            $this->error('创建失败' . $e);
        }
        $this->success('成功', []);
    }

    /**
     * 设置订单状态
     */

    public function setOrderStatus()
    {
        $order_id = $this->request->param('order_id');
        $register_time = $this->request->param('register_time');//登记日期
        $mileage = $this->request->param('mileage');//行驶里程
        $use_type = $this->request->param('use_type');//使用性质:1=营运车,2=非营运
        $car_type = $this->request->param('car_type');//车辆类型:1=轿车,2=SUV
        if (!$register_time || !$mileage || !$use_type || !$car_type) {
            $this->error('参数错误');
        }
        $orderModel = new Order();

        if ($orderModel->where('id', $order_id)->update(['status' => 6, 'register_time' => $register_time, 'mileage' => $mileage, 'use_type' => $use_type, 'car_type' => $car_type]) === false) {
            $this->error('参数错误');
        }
        $this->success('成功', []);
    }

    /**
     * 签名照片
     */
    public function addOrderImage()
    {
        $order_id = $this->request->param('order_id');
        $image = $this->request->param('image');
        $orderModel = new Order();
        if ($orderModel->where('id', $order_id)->update(['agreement_image' => $image]) === false) {
            $this->error('参数错误');
        }
        $this->success('成功', []);
    }

    /**
     * 获取异常状态
     */
    public function getOverhaulStatusList()
    {
        $this->success('成功', getOverhaulStatus());
    }

    public function setOrderInfoOverHaulStatus()
    {
        $order_id = $this->request->param('order_id');
        $order_info_id = $this->request->param('order_info_id');//
        $overhaul_remark = $this->request->param('overhaul_remark');//
        $overhaul_remark_image = $this->request->param('overhaul_remark_image');//
        $overhaul_status = $this->request->param('overhaul_status');//

        if (!$order_id) {
            $this->error('无效的订单');
        }

        $orderModel = new Order();
        $orderInfoModel = new OrderInfo();
        $orderInfo = $orderModel->where('id', $order_id)->find();
        if (!in_array($orderInfo['status'], [3, 6, 5])) {
            $this->error('订单状态错误');
        }

//        dd(json_decode($infos,true) );
//         启动事务
        Db::startTrans();
        try {
            $overhaul_remark_images = '';
            if ($overhaul_remark_image) {
                $overhaul_remark_images = explode(',', $overhaul_remark_image);
                foreach ($overhaul_remark_images as $k1 => &$v1) {
                    if ($v1) {
                        if (!strpos($v1, 'watermark')) {
                            $v1 = $v1 . '?watermark/2/fontsize/700/gravity/NorthWest/text/' . base64_encode(date('Y-m-d H:i:s'));
                        }
                    }
//                    $v1 = $v1 ? $v1 . '?watermark/2/fontsize/700/gravity/NorthWest/text/' . base64_encode(date('Y-m-d H:i:s')) : '';
                }
                $overhaul_remark_images = implode(',', $overhaul_remark_images);
            }
            $orderInfoModel->where(['id' => $order_info_id])->update(
                ['overhaul_remark' => $overhaul_remark, 'overhaul_status' => $overhaul_status, 'overhaul_remark_image' => $overhaul_remark_images, 'testing_time' => time()]
            );
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            $this->error('创建失败' . $e);
        }
        $this->success('成功', []);
    }

    /**
     * 添加备注
     * @return void
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function addRemake()
    {
        $is_burn = $this->request->param('is_burn');
        $order_id = $this->request->param('order_id');
        $is_water = $this->request->param('is_water');
        $is_accident = $this->request->param('is_accident');
        $order_remake = $this->request->param('order_remake');
        if (!$is_burn || !$is_water || !$is_accident || !$order_id) {
            $this->error('请选择事故状态');
        }
        if (!$order_remake) {
            $this->error('备注不能为空');
        }
        $orderModel = new Order();
        $orderInfo = $orderModel->where('id', $order_id)->find();
        if (!$orderInfo) {
            $this->error('订单不存在');
        }
        $orderModel->where('id', $order_id)->update(['is_burn' => $is_burn, 'is_water' => $is_water, 'is_accident' => $is_accident, 'order_remake' => $order_remake, 'status' => 5]);
        $this->success('成功', []);
    }

    public function addCarSelect()
    {
        if (!$this->request->param('name')) {
            $this->error('请填写车辆名称');
        }
        if (!$this->request->param('transaction_price')) {
            $this->error('请填写成交价');
        }
        if (!$this->request->param('registration_date')) {
            $this->error('请填写登记年月');
        }
        if (!$this->request->param('mileage')) {
            $this->error('请填写表显里程');
        }
        if (!$this->request->param('emission_standard')) {
            $this->error('请填写排放标准');
        }
        if (!$this->request->param('engine_displacement')) {
            $this->error('请填写排量');
        }
        if (!$this->request->param('transmission')) {
            $this->error('请填写挡位类型');
        }
        if (!$this->request->param('license_region')) {
            $this->error('请填写牌照属地');
        }
        if (!$this->request->param('seating_capacity')) {
            $this->error('请填写座位数');
        }
        if (!$this->request->param('exterior_color')) {
            $this->error('请填写颜色');
        }
        if (!$this->request->param('transaction_date')) {
            $this->error('请填写成交日期');
        }
        if (!$this->request->param('fans_region')) {
            $this->error('请填写粉丝归属');
        }
        if (!$this->request->param('images')) {
            $this->error('请选择图片');
        }

        $carModel = new CarSelect();
        $carModel->save([
            'user_id' => $this->auth->id,
            'images' => $this->request->param('images') ?? '',
            'name' => $this->request->param('name') ?? '',
            'transaction_price' => $this->request->param('transaction_price') ?? '',
            'registration_date' => $this->request->param('registration_date') ?? '',
            'mileage' => $this->request->param('mileage') ?? '',
            'emission_standard' => $this->request->param('emission_standard'),
            'engine_displacement' => $this->request->param('engine_displacement'),
            'transmission' => $this->request->param('transmission'),
            'license_region' => $this->request->param('license_region'),
            'seating_capacity' => $this->request->param('seating_capacity'),
            'exterior_color' => $this->request->param('exterior_color'),
            'review_text' => $this->request->param('review_text'),
            'review_images' => $this->request->param('review_images') ?? '',
            'transaction_date' => $this->request->param('transaction_date'),
            'fans_region' => $this->request->param('fans_region'),
        ]);
        $this->success('成功', []);
    }

    public function editCarSelect()
    {
        if (!$this->request->param('id')) {
            $this->error('请选择淘车');
        }
        if (!$this->request->param('name')) {
            $this->error('请填写车辆名称');
        }
        if (!$this->request->param('transaction_price')) {
            $this->error('请填写成交价');
        }
        if (!$this->request->param('registration_date')) {
            $this->error('请填写登记年月');
        }
        if (!$this->request->param('mileage')) {
            $this->error('请填写表显里程');
        }
        if (!$this->request->param('emission_standard')) {
            $this->error('请填写排放标准');
        }
        if (!$this->request->param('engine_displacement')) {
            $this->error('请填写排量');
        }
        if (!$this->request->param('transmission')) {
            $this->error('请填写挡位类型');
        }
        if (!$this->request->param('license_region')) {
            $this->error('请填写牌照属地');
        }
        if (!$this->request->param('seating_capacity')) {
            $this->error('请填写座位数');
        }
        if (!$this->request->param('exterior_color')) {
            $this->error('请填写颜色');
        }
        if (!$this->request->param('transaction_date')) {
            $this->error('请填写成交日期');
        }
        if (!$this->request->param('fans_region')) {
            $this->error('请填写粉丝归属');
        }
        if (!$this->request->param('images')) {
            $this->error('请选择图片');
        }

        $carModel = new CarSelect();
        $carDetail = $carModel->where('id', input('id'))->find();
        if (!$carDetail) {
            $this->error('淘车不存在');
        }
        $carDetail->save([
            'user_id' => $this->auth->id,
            'images' => $this->request->param('images') ?? '',
            'name' => $this->request->param('name') ?? '',
            'transaction_price' => $this->request->param('transaction_price') ?? '',
            'registration_date' => $this->request->param('registration_date') ?? '',
            'mileage' => $this->request->param('mileage') ?? '',
            'emission_standard' => $this->request->param('emission_standard'),
            'engine_displacement' => $this->request->param('engine_displacement'),
            'transmission' => $this->request->param('transmission'),
            'license_region' => $this->request->param('license_region'),
            'seating_capacity' => $this->request->param('seating_capacity'),
            'exterior_color' => $this->request->param('exterior_color'),
            'review_text' => $this->request->param('review_text'),
            'review_images' => $this->request->param('review_images') ?? '',
            'transaction_date' => $this->request->param('transaction_date'),
            'fans_region' => $this->request->param('fans_region'),
        ]);
        $this->success('成功', []);
    }

    public function carSelectDetail()
    {
        if (!$this->request->param('id')) {
            $this->error('请选择淘车');
        }
        $carModel = new CarSelect();
        $carDetail = $carModel->where('id', input('id'))->find();
        if (!$carDetail) {
            $this->error('淘车不存在');
        }

        $carDetail['review_images'] = get_app_array_image_url(explode(',', $carDetail['review_images']));
        $carDetail['images'] = get_app_array_image_url(explode(',', $carDetail['images']));
        $this->success('成功', $carDetail);
    }

    public function carSelectList()
    {

        $carModel = new CarSelect();
        $carList = $carModel->order('id desc')->paginate();
        if (!$carList) {
            $this->error('淘车不存在');
        }
        foreach ($carList as &$carDetail) {
            $carDetail['review_images'] = get_app_array_image_url(explode(',', $carDetail['review_images']));
            $carDetail['images'] = get_app_array_image_url(explode(',', $carDetail['images']));
        }

        $this->success('成功', $carList);
    }

    public function carUserSelectList()
    {

        $carModel = new CarSelect();
        $carList = $carModel->where('user_id', $this->auth->id)->paginate();
        if (!$carList) {
            $this->error('淘车不存在');
        }
        foreach ($carList as &$carDetail) {
            $carDetail['review_images'] = get_app_array_image_url(explode(',', $carDetail['review_images']));
            $carDetail['images'] = get_app_array_image_url(explode(',', $carDetail['images']));
        }

        $this->success('成功', $carList);
    }

    /**
     * 添加购车意向
     * @return void
     */
    public function addCarPurchase()
    {
        $model = new CarPurchaseIntention();
        if (!$this->request->param('real_name')) {
            $this->error('请填写真实姓名');
        }
        if (!$this->request->param('phone_number')) {
            $this->error('请填写手机号码');
        }
        if (!$this->request->param('license_city')) {
            $this->error('请填写上牌城市');
        }
        if (!$this->request->param('brand_model')) {
            $this->error('请填写品牌车型');
        }
        if (!$this->request->param('car_age')) {
            $this->error('请填写车龄');
        }
        if (!$this->request->param('preferred_contact_time')) {
            $this->error('请填写希望顾问联系时间');
        }
        if (!$this->request->param('budget')) {
            $this->error('请填写预算');
        }
        $model->save([
            'user_id' => $this->auth->id,
            'real_name' => $this->request->param('real_name'),
            'phone_number' => $this->request->param('phone_number'),
            'budget' => $this->request->param('budget', ''),
            'license_city' => $this->request->param('license_city'),
            'brand_model' => $this->request->param('brand_model'),
            'car_age' => $this->request->param('car_age'),
            'preferred_contact_time' => $this->request->param('preferred_contact_time'),
            'special_requirements' => $this->request->param('special_requirements', ''),
            'createtime' => time()
        ]);
        $this->success('成功');
    }

    public function getCarPurchaseDetail()
    {
        $id = input('id');
        if (!$id) {
            $this->error('错误');
        }
        $model = new CarPurchaseIntention();
        $detail = $model->where('id', $id)->find();
        if (!$detail) {
            $this->error('数据不存在');
        }
        $this->success('成功', $detail);
    }

    /**
     * Author: renyixu
     * Date: 2025/5/8
     * Time: 上午9:49d
     * @return void
     * @throws DbException
     */
    public function getCarPurchaseList()
    {
        $model = new CarPurchaseIntention();
        $detail = $model->order('id desc')->paginate();
        $this->success('成功', $detail);
    }

    public function generateDoc($signatureUrl, $vinCode)
    {
// 接收参数
//        $signatureUrl = input('signature_url'); // 签名图片URL
        $signatureUrl = $signatureUrl . '?imageView2/2/w/150'; // 签名图片URL
////        $vinCode = input('vin');               // VIN码
//        $vinCode = 'LFMG1E728KS083360';               // VIN码

        // 设置路径（按实际调整）
        $templatePath = ROOT_PATH . 'public/static/authorization_template.png';
        $fontPath = ROOT_PATH . 'public/static/simsun.ttf';
        $outputFile = ROOT_PATH . 'public/uploads/auth_docs/' . date('YmdHis') . '_' . mt_rand(1000, 9999) . '.jpg';

        // 创建目录
        if (!is_dir(dirname($outputFile))) {
            mkdir(dirname($outputFile), 0755, true);
        }

//        try {
        // ============ 修复exif_imagetype错误 ==============
        // 替代exif_imagetype的验证方法
        $tempSign = tempnam(sys_get_temp_dir(), 'sign_');
        file_put_contents($tempSign, file_get_contents($signatureUrl));

        // 使用GD库验证图片
        if (!@imagecreatefromstring(file_get_contents($tempSign))) {
            return json(['code' => 500, 'msg' => '签名图片格式错误']);
        }
        // ==============================================

        // 创建图像对象
        $image = Image::open($templatePath);

        // 1. 添加签名
        $image->water($tempSign, [790, 1980]);

        // 2. 添加VIN码（车架号下方）
        $vinText = $vinCode; // 或 "车架号: ".$vinCode
        $image->text($vinText, $fontPath, 20, '#000000', [820, 2080]);

        // 3. 添加日期
        $dateText = date('Y年m月d日');
        $image->text($dateText, $fontPath, 20, '#000000', [820, 2140]);

        $image->save($outputFile, 'jpg', 95);

        // 清理临时文件
        unlink($tempSign);

        // 返回生成的图片URL
        return request()->domain() . str_replace(ROOT_PATH . 'public', '', $outputFile);
//
//        } catch (\Exception $e) {
//            return json(['code' => 500, 'msg' => '合成失败: ' . $e->getMessage()]);
//        }

    }

    public function getMaintenance()
    {
        $model = new Maintenance();
        $list = $model->where('status', 1)->select();
        foreach ($list as $item) {
            Maintenance::update(['status' => 2], ['id' => $item['id']]);
            if ($item['type'] == 1) {
                // 创建 Guzzle 客户端
                $client = new Client([
                    'base_uri' => 'http://39.106.69.73:8078/lemon-report',
//            'base_uri' => 'https://oapi.lemonstea.com',
                    'timeout' => 10.0,
                    'headers' => [
                        'Content-Type' => 'application/json',
                        'Accept' => 'application/json'
                    ]
                ]);
                // 准备请求参数
                $requestParams = [
                    'spno' => '1094861270433792',
                    'phone' => '15888888888',
                    'paytype' => 2,
                    'product' => 2,
                    'vin' => $item['vin'],
                    'dpic' => get_app_image_url($item['driving_license_image']),//行驶证图片
                    'socialCreditCode' => '91310000MA1FPFRF44',
                    'companyName' => '极易净水科技',
                    'authInfoType' => 1,
                    'imageType' => 1,
                    'reptime' => date('YmdHis'),
                    'authFile' => $item['letter_of_auth_image'],//授权书
                ];

                // 计算签名
                $skey = 'testkey2021';
                $requestParams['sign'] = $this->generateSign($requestParams, $skey);

                // 发送 POST 请求
                $response = $client->post('/lemon-report/report/v3/getToken', [
                    'json' => $requestParams
                ]);

                // 处理响应
                $statusCode = $response->getStatusCode();
                $responseBody = $response->getBody()->getContents();
//        dd($responseBody);
                $responseData = json_decode($responseBody, true);  // 转换为关联数组

                if (!isset($responseData['token'])) {
                    Maintenance::update(['status' => 4,'response'=>$responseBody], ['id' => $item['id']]);
                    continue;
                }
                //{
                //		"msgcode": "0000",
                //		"msgcontent": "成功",
                //		"spno": "1094861270433792",
                //		"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0IjoyLCJwaG9uZSI6IjE1ODg4ODg4ODg4IiwidmluIjoiTEZNRzFFNzI4S1MwODMzNjAiLCJzcG5vIjoiMTA5NDg2MTI3MDQzMzc5MiIsImV4cCI6MTc0ODg2ODE4NywicGF5dHlwZSI6Mn0.LZBvAKm7ozEFC2tbVjn03C3HrjV-6la1Pmt3hC4PtA4",
                //		"checkno": "717116009743257600"
                //	}
                $requestParams = [
                    'spno' => '1094861270433792',   // 平台分配的服务商编码（15位）
                    'phone' => '15888888888',       // 服务商注册手机号（11位）
                    'token' => $responseData['token'], // 报告申请接口返回的业务令牌（240位）
                    'checkno' => $responseData['checkno'],      // 报告申请接口返回的查询流水号（20位）
                    'vin' => $item['vin'], // 17位VIN码
                    'reptime' => date('YmdHis'),      // 当前时间，格式：YYYYMMDDHHMMSS
                ];

                // 2. 计算签名
                $skey = 'testkey2021'; // 平台分配的密钥
                $requestParams['sign'] = $this->generateSign1($requestParams, $skey);

                // 3. 构建查询字符串
                $queryString = http_build_query($requestParams);

                // 4. 发送GET请求
//        $url = 'https://oapi.lemonstea.com/lemon-report/report/getReport?' . $queryString;
                $url = 'http://39.106.69.73:8078/lemon-report/report/getReport?' . $queryString;
                Maintenance::update(['status' => 3, 'url' => $url,'response'=>$responseBody], ['id' => $item['id']]);
            }elseif ($item['type'] == 2){
               $this->getBatteryOrder($item);
            }elseif ($item['type'] == 3){
               $this->getWBOrder($item);
            }

        }
    }
    public function getWBOrder($data)
    {
        $client = new Client([
            'base_uri' => 'http://39.106.69.73:8078/lemon-report',
//            'base_uri' => 'https://oapi.lemonstea.com',
            'timeout' => 10.0,
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ]
        ]);
        // 准备请求参数
        $requestParams = [
            'spno' => '1094861270433792',
            'phone' => '15888888888',
            'paytype' => 2,
            'product' => 7,
            'vin' => $data['vin'],
            'dpic' => get_app_image_url($data['driving_license_image']),//行驶证图片
            'reptime' => date('YmdHis'),
        ];

        // 计算签名
        $skey = 'testkey2021';
        $requestParams['sign'] = $this->generateSign($requestParams, $skey);

        // 发送 POST 请求
        $response = $client->post('/lemon-report/maintenance/created', [
            'json' => $requestParams
        ]);

        // 处理响应
        $statusCode = $response->getStatusCode();
        $responseBody = $response->getBody()->getContents();

        $responseData = json_decode($responseBody, true);  // 转换为关联数组
        if (isset($responseData['msgcode'])&&$responseData['msgcode']=='0000'){
            $requestParams = [
                'spno' => '1094861270433792',   // 平台分配的服务商编码（15位）
                'phone' => '15888888888',       // 服务商注册手机号（11位）
                'checkno' => $responseData['data']['checkno'],      // 报告申请接口返回的查询流水号（20位）
                'vin' => $data['vin'], // 17位VIN码
                'reptime' => date('YmdHis'),      // 当前时间，格式：YYYYMMDDHHMMSS
            ];

            $skey = 'testkey2021';
            $signString = $requestParams['spno']
                . $requestParams['phone']
                . $requestParams['checkno']
//                . $data['vin']
                . $skey
                . $requestParams['reptime'];

            // 计算签名

            $requestParams['sign'] = md5($signString);

            // 3. 构建查询字符串
            $queryString = http_build_query($requestParams);

            // 4. 发送GET请求
//        $url = 'https://oapi.lemonstea.com/lemon-report/report/getReport?' . $queryString;
            $url = 'http://39.106.69.73:8078/lemon-report/maintenance/getReport?' . $queryString;
            Maintenance::update(['status' => 3,'url'=>$url,'response'=>$responseBody], ['id' => $data['id']]);
        }else{
            Maintenance::update(['status' => 4,'response'=>$responseBody], ['id' => $data['id']]);
        }
        return $responseData;
    }

    public function getBatteryOrder($data)
    {
        $client = new Client([
            'base_uri' => 'http://39.106.69.73:8078/lemon-report',
//            'base_uri' => 'https://oapi.lemonstea.com',
            'timeout' => 10.0,
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ]
        ]);
        // 准备请求参数
        $requestParams = [
            'spno' => '1094861270433792',
            'phone' => '15888888888',
            'paytype' => 2,
            'product' => 8,
            'vin' => $data['vin'],
            'dpic' => get_app_image_url($data['driving_license_image']),//行驶证图片
            'reptime' => date('YmdHis'),
        ];

        // 计算签名
        $skey = 'testkey2021';
        $requestParams['sign'] = $this->generateSign($requestParams, $skey);

        // 发送 POST 请求
        $response = $client->post('/lemon-report/newEnergy/created', [
            'json' => $requestParams
        ]);

        // 处理响应
        $statusCode = $response->getStatusCode();
        $responseBody = $response->getBody()->getContents();

//        dd($responseBody);
        $responseData = json_decode($responseBody, true);  // 转换为关联数组
        if (isset($responseData['msgcode'])&&$responseData['msgcode']=='0000'){
            $requestParams = [
                'spno' => '1094861270433792',   // 平台分配的服务商编码（15位）
                'phone' => '15888888888',       // 服务商注册手机号（11位）
                'checkno' => $responseData['data']['checkno'],      // 报告申请接口返回的查询流水号（20位）
                'vin' => $data['vin'], // 17位VIN码
                'reptime' => date('YmdHis'),      // 当前时间，格式：YYYYMMDDHHMMSS
            ];

            $skey = 'testkey2021';
            $signString = $requestParams['spno']
                . $requestParams['phone']
                . $requestParams['checkno']
//                . $data['vin']
                . $skey
                . $requestParams['reptime'];

            // 计算签名

            $requestParams['sign'] = md5($signString);

            // 3. 构建查询字符串
            $queryString = http_build_query($requestParams);

            // 4. 发送GET请求
//        $url = 'https://oapi.lemonstea.com/lemon-report/report/getReport?' . $queryString;
            $url = 'http://39.106.69.73:8078/lemon-report/newEnergy/getReport?' . $queryString;
            Maintenance::update(['status' => 3,'url'=>$url,'response'=>$responseBody], ['id' => $data['id']]);
        }else{
            Maintenance::update(['status' => 4,'response'=>$responseBody], ['id' => $data['id']]);
        }
        return $responseData;
    }
    public function getBatteryOrderDetail()
    {
        $checkno = '725441305085087744';
        $client = new Client([
            'base_uri' => 'http://39.106.69.73:8078/lemon-report',
//            'base_uri' => 'https://oapi.lemonstea.com',
            'timeout' => 10.0,
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ]
        ]);
        // 准备请求参数
        $requestParams = [
            'spno' => '1094861270433792',
            'phone' => '15888888888',
            'checkno' => $checkno,
            'reptime' => date('YmdHis'),
        ];
        $skey = 'testkey2021';
        $signString = $requestParams['spno']
            . $requestParams['phone']
            . $requestParams['checkno']
            . $skey
            . $requestParams['reptime'];

        // 计算签名

        $requestParams['sign'] = md5($signString);

        // 发送 POST 请求
        $response = $client->get('/lemon-report/newEnergy/getReportStatus', ['query' => $requestParams]);
        var_dump($requestParams);
        // 处理响应
        $statusCode = $response->getStatusCode();
        $responseBody = $response->getBody()->getContents();

//        dd($responseBody);
        $responseData = json_decode($responseBody, true);  // 转换为关联数组
        var_dump($responseData);
        return $responseData;
    }

    function generateSign(array $params, string $skey): string
    {
        $signString = $params['spno']
            . $params['phone']
            . $params['paytype']
            . $params['product']
            . $params['vin']
            . $params['dpic']
            . $skey
            . $params['reptime'];

        return md5($signString);
    }

    function generateSign1(array $params, string $skey): string
    {
        // 按顺序拼接参数
        $signString = $params['spno']
            . $params['phone']
            . $params['token']
            . $params['checkno']
            . $params['vin']
            . $skey
            . $params['reptime'];

        return md5($signString); // 32位小写MD5
    }

    public function getMaintenanceOrderList()
    {
        $model = new Maintenance();
        $list = $model->where('user_id', $this->auth->id)->whereIn('status',[1,2,3,4])->where('expire_time', '>', date('Y-m-d H:i:s'))->order('id desc')->paginate();
        foreach ($list as $item) {
            // 将时间戳转换为日期格式
            $item->createtime = date('Y-m-d H:i:s', $item->createtime);
            $item->driving_license_image = get_app_image_url($item->driving_license_image);
            $item->letter_of_auth_image = get_app_image_url($item->letter_of_auth_image);
            $item->signature_image = get_app_image_url($item->signature_image);
            // ... 其他操作
        }
        $this->success('获取成功', $list);
    }

    public function getBDAccessToken()
    {
        $redis = new Redis([
            'host' => '127.0.0.1',
            'port' => 6379,
            'password' => '123123',
            'select' => 0]);
        $bd_access_token = $redis->get('bd_access_token');
        if ($bd_access_token) {
            return $bd_access_token;
        }

        $client = new Client([
            'base_uri' => 'https://aip.baidubce.com',
            'timeout' => 30,
            'verify' => false, // 等同于 CURLOPT_SSL_VERIFYPEER=false
        ]);

        try {
            $response = $client->post('/oauth/2.0/token', [
                'query' => [
                    'client_id' => 'ZzD9cKHAqGsZVioem43RUzbB',   // 替换为实际值
                    'client_secret' => 'EXY8DgGXN2xgKhfQzXquBlLOzHVImNmm', // 替换为实际值
                    'grant_type' => 'client_credentials'
                ],
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Accept' => 'application/json'
                ]
            ]);

            $return = $response->getBody()->getContents();
            $redis->set('bd_access_token', json_decode($return)->access_token, 86400 * 28);
            return json_decode($return)->access_token;
        } catch (RequestException $e) {
            // 错误处理（根据需求添加）
            return $e->getMessage();
        }
    }

    public function getVinCode()
    {
        $image = input('image');
        if (!$image) {
            $this->error('请上传图片');
        }
        $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/vin_code?access_token=' . $this->getBDAccessToken();
        $data['url'] = $image;

        try {
            $client = new Client([
                'verify' => false, // 禁用 SSL 验证 (生产环境建议开启)
                'timeout' => 30
            ]);

            $response = $client->post($url, [
                'form_params' => $data, // 自动处理表单数据
            ]);

            $this->success('', \Qiniu\json_decode($response->getBody()->getContents()));

        } catch (RequestException $e) {
            // 错误处理（根据实际需求定制）
            return json_encode(['error' => $e->getMessage()]);
        }
    }

}
